<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽排序</title>
    <style>
        ul{
            list-style: none;
            width: 200px;
        }
        .list-item{
            background-color: blueviolet;
            margin-top: 10px;
            height: 30px;
            line-height: 30px;
            border: 1px solid  #ccc;
            border-radius: 10px;
            padding-left: 20px;
        }
        .moving{
            background: transparent;
            color: transparent;
            border: 1px dashed #ccc;
        }
    </style>
</head>
<body>
    <ul class="list">
        <li draggable="true" class="list-item" >1</li>
        <li draggable="true" class="list-item" >2</li>
        <li draggable="true" class="list-item" >3</li>
        <li draggable="true" class="list-item" >4</li>
        <li draggable="true" class="list-item" >5</li>
    </ul>
    <script>
        const list = document.querySelector('.list');
        let sourceNode ;
        list.ondragstart= (e)=>{
            setTimeout(()=>{
                e.target.classList.add('moving');
            },0)
            e.dataTransfer.effectAllowed = 'move';
            sourceNode = e.target;
        }
        list.ondragenter= (e)=>{
            e.preventDefault();
        }

        list.ondragenter=e=>{
            e.preventDefault();
            if(e.target===list || e.target === sourceNode){
                return;
            }
            const children = [...list.children];
            const sourceIndex = children.indexOf(sourceNode);
            const targetIndex = children.indexOf(e.target);
            if(sourceIndex<targetIndex){
                // 往下拖动
                list.insertBefore(sourceNode,e.target.nextElementSibling)
            }else{
                list.insertBefore(sourceNode,e.target)
            }
            console.log(e)
        }
        list.ondragend=e=>{
            e.target.classList.remove('moving');
        }
    </script>
</body>
</html>